package com.sny.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author:WangKeSheng
 * @Description:http工具类
 * @Date:2020/7/14 14:22
 * @Modified:
 */
@Slf4j
@Component
public class RestHttpUtils {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * https 请求 GET
     *
     * @param url     地址
     * @param dataMap 请求参数集合
     * @return String 类型
     */
    public String getHttp(String url, Map<String, Object> dataMap) {
        log.info("getHttp url:{}", url);
        // 返回值类型
        String result;
        if (dataMap != null) {
            Iterator<Map.Entry<String, Object>> iterator = dataMap.entrySet().iterator();
            StringBuffer sb = new StringBuffer();
            sb.append("?");
            while (iterator.hasNext()) {
                Map.Entry<String, Object> e = iterator.next();
                String key = e.getKey();
                String value = e.getValue() == null ? "" : e.getValue().toString();
                sb.append(key + "=").append(value).append("&");
            }
            url = url + sb.toString().substring(0, url.length() - 1);
        }
        try {
            result = restTemplate.getForObject(url, String.class);
            return result;
        } catch (RestClientException e) {
            log.error("RestHttpUtils getHttp error--->", e);
        }
        return null;
    }

    /**
     * https 请求 GET
     *
     * @param url            地址
     * @param postParameters 请求参数
     * @param headersMap     请求头信息
     * @return String 类型
     */
    public String postHttp(String url, MultiValueMap<String, Object> postParameters, Map headersMap) {
        log.info("postHttp url:{}", url);
        String result = null;
        HttpEntity<MultiValueMap<String, Object>> requestEntity = null;
        if (postParameters == null) {
            postParameters = new LinkedMultiValueMap<>();
        }
        if (headersMap == null) {
            headersMap = new HashMap();
        }

        // 设置·header信息
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAll(headersMap);
        requestEntity = new HttpEntity<>(postParameters, requestHeaders);
        try {
            result = restTemplate.postForObject(url, requestEntity, String.class);
            return result;
        } catch (RestClientException e) {
            log.error("RestHttpUtils getHttp error--->", e);
        }
        return null;
    }
}
